package cn.rocksolid.sport.common.http;

import cn.rocksolid.sport.common.Constant.RockSolidHttpCorsProp;
import cn.rocksolid.sport.common.context.RockSolidContext;
import cn.rocksolid.sport.common.context.RockSolidContextHolder;
import cn.rocksolid.sport.common.error.RSE;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * RockSolid context filter based on shiro framework
 *
 * @author Axl Zhao
 * @email axl.zhao@163.com
 */
public class RockSolidAuthFilter extends AuthenticatingFilter {

  private static final Logger LOGGER = LoggerFactory.getLogger(RockSolidAuthFilter.class);

  private final RockSolidHttpCorsConfig corsConfig;

  public RockSolidAuthFilter(RockSolidHttpCorsConfig corsConfig) {
    this.corsConfig = corsConfig;
  }

  @Override
  protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
    RockSolidContext ctx = RockSolidContextHolder.getContext();
    if (StringUtils.isBlank(ctx.getToken())) {
      LOGGER.warn("Create token failure");
      return null;
    }
    return new RockSolidContextToken(ctx.getToken());
  }

  @Override
  protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    return (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name()));
  }

  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    RockSolidContext ctx = RockSolidContextHolder.getContext();
    if (StringUtils.isBlank(ctx.getToken()) || null == ctx.getAccessType()) {
      LOGGER.warn("Can not retrieve valid access token or access type");
      error401(response);
      return false;
    }
    return executeLogin(request, response);
  }

  @Override
  protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException exp, ServletRequest request,
          ServletResponse response) {
    error401(response);
    return false;
  }

  private void error401(final ServletResponse servletResponse) {
    if (servletResponse instanceof HttpServletResponse) {
      HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
      httpServletResponse.setHeader(RockSolidHttpCorsProp.HDR_MAX_AGE, String.valueOf(corsConfig.getMaxAge()));
      httpServletResponse.setHeader(RockSolidHttpCorsProp.HDR_ALLOW_CREDENTIALS,
              String.valueOf(corsConfig.isAllowCredentials()));
      httpServletResponse.setHeader(RockSolidHttpCorsProp.HDR_ALLOWED_HEADERS,
              String.join(RockSolidHttpCorsProp.VAL_SEPARATOR, corsConfig.getAllowedHeaders()));
      httpServletResponse.setHeader(RockSolidHttpCorsProp.HDR_ALLOWED_ORIGIN,
              String.join(RockSolidHttpCorsProp.VAL_SEPARATOR, corsConfig.getAllowedOriginPatterns()));
      httpServletResponse.setHeader(RockSolidHttpCorsProp.HDR_ALLOWED_METHODS,
              String.join(RockSolidHttpCorsProp.VAL_SEPARATOR, corsConfig.getAllowedMethods()));
      httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    try (PrintWriter printWriter = servletResponse.getWriter()) {
      printWriter.print(
              JSON.toJSON(RockSolidExceptionHandler.error(RSE.UNAUTHORIZED.code(), RSE.UNAUTHORIZED.message())));
      printWriter.flush();
    } catch (IOException ioe) {
      LOGGER.warn(String.format("Try to give back response gonna I/O exception, caused by: %s", ioe.getMessage()), ioe);
    }
  }
}
